package com.yantong.controller.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.yantong.annotation.Auth;
import com.yantong.annotation.LoginUser;
import com.yantong.config.LocalRedis;
import com.yantong.constant.*;
import com.yantong.controller.BaseController;
import com.yantong.enums.PayChannelEnum;
import com.yantong.exception.BDException;
import com.yantong.mapper.*;
import com.yantong.pay.yfz.pay.YFZPayutil;
import com.yantong.utils.HttpUtil;
import com.yantong.pojo.*;
import com.yantong.pojo.vo.AfterSaleProductVo;
import com.yantong.pojo.vo.WeiXinUserInfoVo;
import com.yantong.result.ResultVo;
import com.yantong.service.*;
import com.yantong.utils.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 待整理的接口
 * @author: juzi
 * @date: 2021/10/25
 * @time: 16:12
 */
@Controller
@RequestMapping("/wxapi")
public class ApiOtherController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(ApiOtherController.class);


    @Autowired
    private ConfigService configService;
    @Autowired
    private CentreService centreService;
    @Autowired
    private WxService wxService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private TicketService ticketService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private HeadTabService headTabService;
    @Autowired
    private CentreTerminalMapper centreTerminalMapper;
    @Autowired
    private MemberProductAuthorityService memberProductAuthorityService;
    @Autowired
    private OrderSplitInfoMapper orderSplitInfoMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private XLoginInfoMapper xLoginInfoMapper;
    @Autowired
    private UserRegistrationService userRegistrationService;
    @Autowired
    private YFZPayutil yfzPayutil;
    @Autowired
    private PayChannelService payChannelService;
    @Autowired
    private OrderMapper orderMapper;
    @Value("${weixin.pay.notify}")
    private String notifyUrl;
    @Value("${yfz.notify}")
    private String yfzNotifyUrl;
    @Autowired
    private OrderProductMapper orderProductMapper;

    @Autowired
    private LocalRedis localRedis;
    @Autowired
    private OssService ossService;
    @Autowired
    private JuheOrderMapper juheOrderMapper;
    @Autowired
    private JuheOrderRefundMapper juheOrderRefundMapper;
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private TicketRecordMapper ticketRecordMapper;
    @Autowired
    private MemberIntegralService memberIntegralService;
    @Autowired
    private MemberAggregationService memberAggregationService;

    @Autowired
    private MyWxpayService myWxpayService;


    //
//    /**
//     * 本地生活微信支付购买王权会员
//     */
//    @RequestMapping("/life/config")
//    @ResponseBody
//    @Auth
//    public ResultVo getLifeConfig(Long centerId) {
//        LifeConfig config = configService.getLifeConfig(defaultCenterId);
//        return ResultVo.ok().put("data", config);
//    }


    /**
     * 获取微信jssdk配置
     */
    @RequestMapping("/jsconfig")
    @ResponseBody
    public ResultVo getJsConfig(String url, Long centerId){
        logger.info("/jsconfig::::--url=" + url + "centerId = " + centerId);
        Centre centre = centreService.getByKey(centerId);

        //2、获取Ticket
        String jsapi_ticket = wxService.getJsapiTicket(centerId, WxTerminal.TERMINAL_GZH.getTerminal());

        //3、时间戳和随机字符串
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);//随机字符串
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);//时间戳

        //5、将参数排序并拼接字符串
        String str = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + url;

        //6、将字符串进行sha1加密
        String signature = DigestUtils.sha1Hex(str);

        Map<String, String> map = new HashMap<>();
        map.put("signature", signature);
        map.put("nonceStr", noncestr);
        map.put("timestamp", timestamp);
        map.put("appId", centre.getGzhAppid());
        logger.info("/jsconfig::::" + JSONObject.toJSONString(map));
        ResultVo resultVo = new ResultVo();
        resultVo.put("data", JSONObject.toJSONString(map));
        resultVo.put("success", true);
        return resultVo;
    }

    /**
     * 首页初始化接口
     */
    @RequestMapping("/firstinit")
    @ResponseBody
    @Auth
    public ResultVo firstInit(Long memberId) {
        Member member = memberService.getDetail(memberId);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", member);

        if (null == member) {
            return resultVo;
        }

        Member shop = null;
        if (member.getUpshopTid() != null) {
            shop = memberService.getDetail(member.getUpshopTid());
        }
        resultVo.put("shop", shop);

        TradeConfig config = configService.getTradeConfig(member.getCentreId());
        resultVo.put("config", config);
        resultVo.put("time", System.currentTimeMillis());
        return resultVo;
    }

    @ApiOperation(value = "返回商户全局优惠卡优惠的金额")
    @ResponseBody
    @GetMapping("/getDirectorincome")
    public ResultVo getMerchantCardPrice(long mid, String payAmount, String teamSeqId, Long trId) {
        ResultVo resultVo = new ResultVo();
        Member teamMember = memberService.getTmByTeamSeqId(teamSeqId);

        BigDecimal payAmountNew = new BigDecimal(payAmount);
        BigDecimal ticketMoney = BigDecimal.ZERO;
        Double merchantCardPreferentialRatio = 0d;
        if (trId != null) {
            //计算优惠金额
            ticketMoney = orderService.calcTicketAmountJuhepay(trId, payAmountNew, teamMember.getCentreId());
            payAmountNew = payAmountNew.subtract(ticketMoney);
        }

        resultVo.put("ticketMoney", ticketMoney);
        resultVo.put("payAmountNew", payAmountNew);
        resultVo.put("merchantCardPreferentialRatio", merchantCardPreferentialRatio);
        resultVo.put("teamMember", teamMember);
        return resultVo;
    }


    /**
     * 佣金配置信息查询
     */
    @RequestMapping("/commis/config")
    @ResponseBody
    @Auth
    public ResultVo getLifeConfig(Long centreId) {
        LifeConfig config = configService.getLifeConfig(centreId);
        return ResultVo.ok().put("data", config);
    }

    /**
     * 获取子分类  Long parentId(旧版本参数)
     */
    @RequestMapping("/category")
    @ResponseBody
    public ResultVo getCategory(Category category) {
        List<Category> categoryList = categoryService.getListCategory(category);
     /*   List<Category> categoryList = (parentId == null) ?
                categoryService.listCategorys() : categoryService.listCategorys(parentId);*/
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", categoryList);
        return resultVo;
    }

    /**
     * 获取优惠券
     */
    @RequestMapping("/coupon")
    @ResponseBody
    //@Auth(arg = 0)
    public ResultVo getCoupons(Long memberId, Integer status, Integer type, Long industryBrandId, Long productGradeId, Long industryId, int offset, int limit) {
        PageUtils<TicketRecord> coupons = ticketService.listMidRecords(memberId, type, status, industryBrandId, productGradeId, industryId, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", coupons);
        return resultVo;
    }

    /**
     * 确认收货
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/confirmReceived")
    @ResponseBody
    @Auth
    public ResultVo confirmReceived(Long orderId) {

        if (orderId == null) {
            return ResultVo.error();
        }
        if (orderService.confirmReceived(orderId) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();

    }

    /**
     * 确认发货
     *
     * @param orderId
     * @return
     */
    @ResponseBody
    @RequestMapping("/sendGoods")
    @Auth
    public ResultVo sendGoods(Long orderId) {
        if (orderId == null) {
            return ResultVo.error();
        }
        if (orderService.sendGoods(orderId) < 1) {
            return ResultVo.error();
        }
        return ResultVo.ok();
    }

    /**
     * 得到商品购买过头像
     *
     * @param productId
     * @param offset
     * @param limit     传7
     * @return
     */
    @RequestMapping("/getOrderUserHeadImg")
    @ResponseBody
    @Auth
    public ResultVo getOrderUserHeadImg(Long productId, int offset, int limit) {
        PageUtils<OrderHead> list = orderService.getOrderUserHeadImg(productId, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", list);
        return resultVo;
    }

    /**
     * 登录领取优惠券接口
     *
     * @param centreid //服务中心id
     * @param state    //状态 0新用户 1老用户
     * @param memberid //会员编号
     * @return
     */
    @RequestMapping("/logincoup")
    @ResponseBody
    @Auth
    public ResultVo loginCoup(String centreid, String state, Long memberid, Long teamId) {
        ResultVo resultVo = new ResultVo();
        if (StringUtils.isEmpty(centreid) || StringUtils.isEmpty(state) || null == memberid) {
            return resultVo;
        }
        List<Ticket> ticket = null;
        ticket = ticketService.getFirstLoginCoup(centreid, memberid, teamId);

        resultVo.put("data", ticket);
        resultVo.put("success", true);
        return resultVo;
    }

    /**
     * 优惠券领取接口
     *
     * @param memberId
     * @param ticketid
     * @return
     */
    @RequestMapping("/recieveCoup")
    @ResponseBody
    @Auth
    public ResultVo recieveCoup(Long memberId, String ticketid) {
        ResultVo resultVo = new ResultVo();
        if (null == memberId || org.springframework.util.StringUtils.isEmpty(ticketid)) {
            resultVo.put("success", false);
            return resultVo;
        }
        //领取优惠券
        List<String> asList = Arrays.asList(ticketid.split(","));
        ticketService.updateRecord(memberId, asList);
        resultVo.put("success", true);
        return resultVo;
    }

    /**
     * 得到标签信息
     *
     * @return
     */
    @RequestMapping("/getHeadTab")
    @ResponseBody
    public ResultVo getHeadTab() {
        Map<String, Object> map = new HashMap<String, Object>();
        List<HradTab> list = headTabService.getHeadTabListByParams(map);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", list);
        return resultVo;
    }

    /**
     * 供应商售后商品列表
     *
     * @param params
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping("/aftersale/productlist")
    @ResponseBody
    /* @Auth*/
    public ResultVo getAfterSaleProductList(ListAfterProductParams params, Integer offset, Integer limit) {
        PageUtils<AfterSaleProductVo> orders = orderService.listAfterSaleProductList(params, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", orders);
        return resultVo;
    }
    /**
     * 查询商家终端
     */
    @RequestMapping("/query/terminal")
    @ResponseBody
    public ResultVo listCentreTerminal(@ApiIgnore @LoginUser Member member) {
        CentreTerminal centreTerminal = new CentreTerminal();
        centreTerminal.setCentreId(member.getCentreId());
        List<CentreTerminal> list = centreTerminalMapper.selectByAll(centreTerminal);
        if (ValidateUtil.isEmptyCollection(list)) {
            centreTerminal.setCentreId(null);
            list = centreTerminalMapper.selectByAll(centreTerminal);
        }
        return ResultVo.ok().put("data", list);
    }

    /**
     * 根据用户id获取该用户大礼包权限列表
     *
     * @param offset
     * @param limit
     * @param
     * @return
     */
    @ApiOperation(value = "根据用户id获取该用户大礼包权限列表")
    @GetMapping("/memberProductAuthority/selectmemberProductAuthorityList")
    @ResponseBody
    public ResultVo selectActivityList( Long mid, int offset, int limit) {
        ResultVo resultVo = ResultVo.ok();
        return resultVo.put("data",memberProductAuthorityService.selectAllByMember(mid,offset, limit));
    }

    /**
     * 门店收款信息（余额结算，金额结算）
     *
     * @param status    状态0-未发放 1-已发放 2已退款 3已售后退款
     * @param type      订单来源1-线上订单，2-线下支付
     * @param splitType 结算方式1-商户结算（余额），2-交易分账（易票联）
     * @param teamId    门店id
     */
    @RequestMapping("/orderSplitInfo/Page")
    @ResponseBody
    public ResultVo orderSplitInfoPage(Integer status, Integer type, Integer splitType, Long teamId, int offset, int limit) {
        //总额
        BigDecimal totalMoney = orderSplitInfoMapper.selectByStatusAndTypeAndSplitTypeAndTeamId(status, type, splitType, teamId);

        //分页
        Map<String, Object> params = new HashMap<>();
        params.put("status", status);
        params.put("type", type);
        params.put("splitType", splitType);
        params.put("teamId", teamId);
        PageUtils<OrderSplitInfo> pageUtils = new PageUtils<>();
        int total = orderSplitInfoMapper.totalByParams(params);
        pageUtils.setTotal(total);
        pageUtils.setRows(null);
        if (total > 0) {
            pageUtils.setRows(orderSplitInfoMapper.listByParams(params, new RowBounds(offset, limit)));
        }

        Map<String, Object> result = new HashMap<>();
        result.put("totalMoney", totalMoney == null ? 0 : totalMoney);
        result.put("pageUtils", pageUtils);
        return ResultVo.ok().put("data", result);
    }

    /**
     * 获取微信网页登录授权信息
     *
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/authurl")
    @ResponseBody
    public ResultVo getOauthLogin(String redirectUri, String state, Long centerId) {
        logger.info("centerId为：{} , 回调函数为: {}", centerId,redirectUri);
        Centre centre = centreService.getByKey(centerId);
        if (null == centre) {
            centre = centreService.getPlatCenter();
        }
        //第一步：用户同意授权，获取code,会重定向到backUrl
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+centre.getGzhAppid()
                + "&redirect_uri="+ redirectUri
                + "&response_type=code"
                + "&scope=snsapi_userinfo"
                + "&state=STATE#wechat_redirect";

        System.out.println(redirectUri);
//        JSONObject jsonObject = HttpUtil.sendGet(url);

        ResultVo resultVo = new ResultVo();
        resultVo.put("data",url);
        resultVo.put("success", true);
        logger.info(JSON.toJSONString(resultVo));
        return resultVo;
    }




    protected JSONObject doGet(String code, Centre centre) throws ServletException, IOException {
        //接收code
        //第二步：通过code换取网页授权access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                + centre.getGzhAppid()
                + "&secret="+centre.getGzhSecret()
                + "&code="+ code
                + "&grant_type=authorization_code";
        //它会返回一个json数据包
        JSONObject jsonObject = HttpUtil.sendGet(url);
        String openid = jsonObject.getString("openid");
        String token = jsonObject.getString("access_token");
        //第三步：刷新access_token（如果需要）
        //第四步：拉取用户信息(需scope为 snsapi_userinfo)
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
                + "&openid="+openid
                + "&lang=zh_CN";
        JSONObject userInfo = HttpUtil.sendGet(infoUrl);
        return userInfo;
    }


    /**
     * 登录
     * @param mid    用户id
     * @param teamid 门店id
     * @author kanghaixin
     * @date 2018/9/7.15:39
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResultVo getOauthToken(String code, String mobile,Long centreId, String teamid, Long mid, String is_brokerage) throws ServletException, IOException {
        logger.info("==code==" + code + "==centreId==" + centreId + "==teamid==" + teamid + "==mid==" + mid + "==is_brokerage==" + is_brokerage);
        Centre centre = centreService.getByKey(centreId);
        if (null == centre) {
            centre = centreService.getPlatCenter();
        }
        JSONObject jsonObject = doGet(code,centre);
        ResultVo resultVo = new ResultVo();
        String firstLoginIMg = "";
        PlatformConfig config = configService.getConfigByKey(ConfigKey.BASE_CONFIG.name());
        if (config != null) {
            firstLoginIMg = config.getAppFLoginImgUrl();
        }

        WeiXinUserInfoVo weiXinUserInfoVo = JSONObject.parseObject(jsonObject.toJSONString(),WeiXinUserInfoVo.class);
        Member member = memberService.getByOpenId(weiXinUserInfoVo.getOpenid());
        if (member == null) {
            member = memberService.getByUnionId(weiXinUserInfoVo.getUnionid());
        }
        logger.info("公众号授权/用户信息:" + weiXinUserInfoVo.toString());
        String ticket = String.valueOf(new Random().nextInt(999999));
        boolean firstLogin = member == null;
        logger.info("==firstLogin==" + firstLogin);
        if (firstLogin) {
            //首次登录必须传入手机号码
            if(StringUtils.isEmpty(mobile)){
                //将用户手动操作产生的code存入缓存,作为发送验证码所需的验证标识 , 用以防止短信验证码被盗刷
                redisTemplate.opsForValue().set(code,"1",5,TimeUnit.MINUTES);
                return ResultVo.error(BusinessCode.MOBILE_NOT_EXIST);
            }

            //验证手机号是否已通过验证
            String va = redisTemplate.opsForValue().get("sMobile" + mobile);
            if(StringUtils.isEmpty(va)){
                return ResultVo.error(BusinessCode.MOBILE_NOT_VERIFY);
            }

            //查询用户是否已存在(可能在本地生活/其他小程序登陆过)
            member = memberService.getOneByCentreIdAndMobile(centreId,mobile);
            if(null != member){
                member.setOpenid(weiXinUserInfoVo.getOpenid());
                member.setLoginMobile(mobile);
                memberService.updateByPrimaryKeySelective(member);
            }else {
                logger.info("---------------进入注册逻辑=------");
                member = new Member();
                member.setLoginMobile(mobile);
                member.setOpenid(weiXinUserInfoVo.getOpenid());
                member.setAvatar(weiXinUserInfoVo.getHeadimgurl());
                member.setNickname(weiXinUserInfoVo.getNickname());
                member.setProvince(weiXinUserInfoVo.getProvince());
                member.setCity(weiXinUserInfoVo.getCity());
                if (weiXinUserInfoVo.getUnionid() != null) {
                    member.setUnionid(weiXinUserInfoVo.getUnionid());
                }
                member.setTicket(ticket);
                if (StringUtils.isNotEmpty(teamid)) {
                    //门店信息
                    Member mem = memberService.getTmByKey(new Long(teamid));
                    member.setCentreId(mem.getCentreId());
                    member.setTeamid(mem.getId());
                    member.setUpshopName(StringUtils.isEmpty(mem.getRealname()) ? mem.getNickname() : mem.getRealname());
                    member.setUpshopTid(mem.getId());
                }
                logger.info("==mid==" + mid);
                //推荐用户不为空
                if (mid != null) {
                    logger.info("==mid!=nul===" + (mid != null));
                    //查找推荐用户
                    Member mem = memberService.getTmByKey(mid);
                    if (mem != null) {
                        logger.info("==mem!=nul===" + mem.getId());
                        //设置推荐人
                        member.setUserid(mem.getId());
                        logger.info("==mem===" + JSONObject.toJSONString(mem));
                        member.setUserName(StringUtils.isEmpty(mem.getRealname()) ? mem.getNickname() :
                                mem.getRealname());
                        //用户推荐人的推荐人不为空
                        if (mem.getUserid() != null) {
                            //设置上级推荐人
                            member.setUpUserid(mem.getUserid());
                            member.setUpuserName(mem.getUserName());
                        }
                    }

                }
                if (member.getCentreId() == null) {
                    member.setCentreId(centreId);
                }

                logger.info("==member===" + JSONObject.toJSONString(member));
                long id = memberService.saveMember(member);
                logger.info("公众号新增用户成功");
                if (id < 0) {
                    return ResultVo.error();
                }
                redisTemplate.opsForValue().set("isNew:" + id, "true", 7, TimeUnit.DAYS);

                Member memberParam = memberService.getByKey(member.getId());
                //新注册用户特殊业务分支处理（商户的特殊需求）
                UserRegistrationDTO userRegistrationDTO = new UserRegistrationDTO();
                userRegistrationDTO.setMember(memberParam);
                userRegistrationService.userRegistrationBusinessProcess(userRegistrationDTO);
            }


        } else {
            boolean bol = false;
            if (StringUtils.isEmpty(member.getOpenid())) {
                logger.info("公众号授权给openid赋值");
                member.setOpenid(weiXinUserInfoVo.getOpenid());
                logger.info("公众号修改openid赋值成功");
                bol = true;
            }
            if (StringUtils.isEmpty(member.getUnionid()) && ValidateUtil.isNotEmptyString(weiXinUserInfoVo.getUnionid())) {
                member.setUnionid(weiXinUserInfoVo.getUnionid());
                bol = true;
            }
            if (bol) {
                memberService.updateByPrimaryKeySelective(member);
            }
            String s = redisTemplate.opsForValue().get("token:" + member.getId());
            if (StringUtils.isBlank(s)) {
                memberService.setTicket(member.getId(), ticket);
            }
        }

        member.setTicket(null);//不要返回到前端

        String sign = DigestUtils.md5Hex(member.getId() + member.getOpenid());
        JSONObject autoToken = new JSONObject();
        autoToken.put("id", member.getId());
        autoToken.put("oid", member.getOpenid());
        autoToken.put("sign", sign);

        if (member.getGrade() == null) {
            member.setGrade(1);
        }
        resultVo.put("data", member);
        resultVo.put("success", true);
        resultVo.put("firstLogin", firstLogin);
        resultVo.put("firstLoginIMg", firstLoginIMg);
        String authTokenStr = Base64Utils.encodeToString(autoToken.toJSONString().getBytes(StandardCharsets.UTF_8));
        resultVo.put("authToken", authTokenStr);
        //使用LoginUser注解需要
        redisTemplate.opsForValue().set(authTokenStr, member.getId().toString());
        System.err.println(authTokenStr);
        return resultVo;
    }

    /**
     * 供应商统计
     */
    @RequestMapping("/supply/statistic")
    @ResponseBody
    public ResultVo getSupplyStatistic(ShopCountParams params, int limit, int offset) {
        Map<String, Object> supplyCount = orderService.supplyCount(params, limit, offset);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", supplyCount);
        return resultVo;
    }

    /**
     * 本地生活微信支付购买商户优惠卡
     */
    @RequestMapping("/purchase/preferentialCard")
    @ResponseBody
    @Auth
    public ResultVo purchasePreferentialCard(@ApiIgnore @LoginUser Member member,Integer payMethod, HttpServletRequest request) throws Exception {
        String payNo = CommonUtils.getSn("X_OC_D");
        ResultVo resultVo = new ResultVo();
        String desc = "购买商户优惠卡";
        JSONObject attach = new JSONObject();
        attach.put("type", WXPAY_LOCALLIFE_PREFERENTIAL_CARD);
        attach.put("memberId", member.getId());
        attach.put("centreId", member.getCentreId());
        boolean success = false;

        while (!success) {
            try {
                double price = 10.00;
                LifeConfig config = configService.getLifeConfig(member.getCentreId());
                if (config != null) {
                    if (config.getPreferentialCard() != null) {
                        price = Double.parseDouble(config.getPreferentialCard());
                    }
                }

                PayChannel payChannel = payChannelService.getFirstChannel(member.getCentreId());
                logger.info("商户优惠卡购买支付通道查询====" + JSONObject.toJSONString(payChannel));
//                if (StringUtils.isNotBlank(payChannel.getChannelCode()) && payChannel.getChannelCode().equals(PayChannelEnum.YPL.getCode()) && price > 0.01) {
                    Centre centre = centreService.getCentreById(member.getCentreId());
                    Member teamMember = new Member();
                    Order order = new Order();
                    order.setOutTradeNo(payNo);
                    order.setStatus(6);
                    order.setPaystatus(PayStatus.PAYING.getCode());//更改支付状态为支付中
                    order.setPaytype(2);//公众号支付类型
                    order.setOrderType(15); //购买商户优惠卡订单类型
                    order.setNickname(member.getNickname());
                    order.setPayattach(JSON.toJSONString(attach));
                    order.setCentreId(member.getCentreId());
                    orderMapper.insertSelective(order);
                    order.setPayprice(new BigDecimal(price));
                    List<OrderProduct> orderProductList = new ArrayList<>();
                    OrderProduct orderProduct = new OrderProduct();
                    orderProduct.setProductId(99L);
                    orderProduct.setProductName("购买商户优惠卡");
                    orderProduct.setPrice(BigDecimal.valueOf(price));
                    orderProduct.setTotal(1);
                    orderProductList.add(orderProduct);
                XLoginInfo xLoginInfo = new XLoginInfo();
                xLoginInfo.setMobile(member.getLoginMobile());
                xLoginInfo = xLoginInfoMapper.selectOne(xLoginInfo);
                member.setAppOpenid(xLoginInfo.getOpenId());
                    return yfzPayutil.getPayConfig(order, price, centre, orderProductList, member, JSON.toJSONString(attach), payMethod == null ? 1 : payMethod, true, yfzNotifyUrl, request, teamMember);
//                } else {
//
//                    WxPayMpOrderResult result = myWxpayService.createJSPayRequest(member.getOpenid(), desc, payNo
//                            , price, notifyUrl, CusAccessObjectUtil.getIpAddress(request), attach.toJSONString());
//                    resultVo.put("success", true);
//                    resultVo.put("data", result);
//                }
//                success = true;
            } catch (Exception e) {
                return ResultVo.error(e.getMessage());
            }
        }
        return resultVo;
    }

    /**
     * 分享图片
     */
    @RequestMapping("/getShareImg")
    @ResponseBody
    @Auth
    public ResultVo getShareImg(String id, String payNumber) {
        List<OrderProduct> list = null;
        //查询缓存
        Object img = null;
        if (StringUtils.isNotEmpty(id)) {
            list = orderProductMapper.getProductListByOrderId(Long.valueOf(id));
            img = localRedis.get("share_img_det" + id);
        } else {
            list = orderProductMapper.getByPayNo(payNumber);
            img = localRedis.get("share_img_det" + payNumber);
        }
        String key = null;
        if (img != null) {
            if (StringUtils.isNotEmpty(id)) {
                key = localRedis.get("share_img_det" + id).toString();
            } else {
                key = localRedis.get("share_img_det" + payNumber).toString();
            }
        } else {
            InputStream is = ImageUtils.sharelapImage(list);
            if (is == null) {
                logger.error("输入流为空");
            } else {
                key = ossService.uploadImg(is, null);
            }
            if (StringUtils.isNotEmpty(id)) {
                localRedis.setByDay("share_img_det" + id, key, 3);
            } else {
                localRedis.setByDay("share_img_det" + payNumber, key, 3);
            }
        }
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", key);
        return resultVo;
    }

    /**
     * 本地生活微信支付购买王权会员
     */
    @RequestMapping("/trade/config")
    @ResponseBody
    @Auth
    public ResultVo getTradeConfig(Long centerId) {
        TradeConfig config = configService.getTradeConfig(centerId);
        return ResultVo.ok().put("data", config);
    }

    /**
     * 得到推荐用户列表
     *
     * @param mid
     * @param payStu
     * @return
     */
    @RequestMapping("/mem/getMemByUserId")
    @ResponseBody
    @Auth
    public ResultVo getMemByUserId(Long mid, Integer payStu) {
        ResultVo resultVo = new ResultVo();

        Map params = new HashMap();
        if (mid != null) {
            params.put("userid", mid);
        }
        List<Member> list = memberService.getMemByUserId(params);
        resultVo.put("success", true);
        resultVo.put("data", list);
        return resultVo;
    }

    /**
     * 聚合支付列表
     */
    @GetMapping("/juhepay/list")
    @ResponseBody
    public ResultVo juhepayList(Long mid, Long teamId, int offset, int limit) {
        PageUtils<JuheOrder> juheOrderList = orderService.juheOrdersList(mid, teamId, null, null, null, null, null, null, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", juheOrderList);
        return resultVo;
    }

    /**
     * 根据聚合码查用户信息
     */
    @RequestMapping("/juhepay/member")
    @ResponseBody
    public ResultVo juhepayMember(String teamSeqId) {
        Member teamMember = memberService.getTmByTeamSeqId(teamSeqId);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", teamMember);
        return resultVo;
    }

    /**
     * 聚合支付获取优惠券
     */
    @RequestMapping("/juhepay/coupon")
    @ResponseBody
    public ResultVo juhepayCoupon(String openId, String payMoney, String teamSeqId) {
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        Member member = memberService.getByOpenId(openId);
        Member teamMember = memberService.getTmByTeamSeqId(teamSeqId);
        if (member != null && teamMember != null) {
            List<TicketRecord> coupons = ticketService.getTicketRecordsJuHe(member.getId(), payMoney, teamMember.getId());
            resultVo.put("data", coupons);
            return resultVo;
        }
        resultVo.put("data", null);
        return resultVo;
    }

    /**
     * 优惠券详情
     */
    @GetMapping("/coupon/detail")
    @ResponseBody
    public ResultVo couponDetail(Long ticketId) {
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        if (ticketId == null) {
            resultVo.put("data", null);
            return resultVo;
        }
        Ticket ticket = ticketService.getByKey(ticketId);
        resultVo.put("data", ticket);
        return resultVo;
    }

    /**
     * 聚合支付退款申请
     */
    @GetMapping("/juhe/refund")
    @ResponseBody
    @Transactional(rollbackFor = Exception.class)
    public ResultVo juherRefund(@ApiIgnore @LoginUser Member member, String outTradeNo, String reason, String images) throws Exception {
        JuheOrder juheOrder = juheOrderMapper.selectOrderByOutTradeNo(outTradeNo);
        if (juheOrder == null) {
            throw new BDException("聚合支付订单不存在！");
        }
        if (juheOrder.getPaystatus() != 2) {
            throw new BDException("只有状态为支付成功的订单才能发起退款！");
        }
        String sn = DateUtils.format(new Date(), "ddHHmmss");
        String refundNo = "JH_REFUND".concat(sn);
        JuheOrderRefund juheOrderRefund = new JuheOrderRefund();
        juheOrderRefund.setReason(reason);
        juheOrderRefund.setImages(images);
        juheOrderRefund.setRefundNo(refundNo);
        juheOrderRefund.setJuheOrderId(juheOrder.getId());
        juheOrderRefund.setPayOpenId(member.getOpenid());
        juheOrderRefund.setAid(member.getId());
        juheOrderRefund.setAname(ValidateUtil.isNotEmptyString(member.getRealname()) ? member.getRealname() : member.getNickname());
        juheOrderRefund.setStatus(0);
        juheOrderRefund.setApplyPrice(juheOrder.getPayprice());
        juheOrderRefund.setPayChannel(1);
        juheOrderRefund.setCentreId(juheOrder.getCenterId());
        juheOrderRefund.setTeamId(juheOrder.getTeamId());
        juheOrderRefund.setOutTradeNo(juheOrder.getOutTradeNo());
        juheOrderRefundMapper.insertSelective(juheOrderRefund);
        juheOrder.setRefundNo(refundNo);
        juheOrder.setPaystatus(6);
        juheOrder.setRefundid(juheOrderRefund.getId());
        juheOrderMapper.updateById(juheOrder);
        return ResultVo.ok();
    }

    /**
     * 优惠券核销
     *
     * @param ticketParam
     * @return
     */
    @ApiOperation(value = "优惠券核销")
    @PostMapping("/writeOff")
    @ResponseBody
    @Auth
    public ResultVo writeOff(@LoginUser Member member,@RequestBody TicketParam ticketParam) {
        ResultVo resultVo = ResultVo.ok();
        return resultVo.put("data",ticketService.writeOffTicket(member,ticketParam));
    }

    /**
     * 优惠券转赠
     */
    @GetMapping("/giving/ticket")
    @ResponseBody
    @Auth
    public ResultVo givingTicket(Long centreId, String phone, Long trId) {
        Member memberResult = memberMapper.getByMobileCenter(phone, centreId);

        if (memberResult == null) {
            return ResultVo.error(phone + "不是该商户下的用户，不能赠送");
        }

        TicketRecord tr = ticketService.getRecordByKey(trId);
        tr.setUseTime(new Date());
        tr.setCountUsed(tr.getCountUsed() + 1);
        if (tr.getCountUsed() >= tr.getCount()) {
            tr.setStatus(TicketStatus.USED.getStatus());
        }
        ticketService.updateRecord(tr);
        ticketService.addRecordUseInfo(tr, 1, null, "优惠券转赠", new TicketRecordUse());


        Ticket ticket = ticketService.getByKey(tr.getTicketId());
        if (ticket == null) {
            return ResultVo.error("优惠券信息不存在");
        }

        if (ticket.getStock() < 1) {
            throw new BDException(BusinessCode.TICKET_SEND_OVER_ERROR);
        }

        TicketRecord trParam = new TicketRecord();
        trParam.setTicketId(ticket.getId());
        trParam.setMid(memberResult.getId());
        trParam.setStatus(0);
        trParam.setType(ticket.getType());
        Date now = new Date();
        trParam.setStartTime(now);
        trParam.setEndTime(ticket.getEndTime());
        if (ticket.getPeriod() != null) {
            trParam.setEndTime(DateUtils.getAddDayDate(now, ticket.getPeriod()));
        }
        trParam.setGetTime(now);
        trParam.setNum(1);
        trParam.setCentreId(ticket.getCentreId());
        trParam.setTeamId(ticket.getTeamId());
        ticketRecordMapper.insertSelective(trParam);

        return ResultVo.ok();
    }

    /**
     * 优惠券手动核销
     */
    @GetMapping("/use/ticket")
    @ResponseBody
    @Auth
    @Transactional(rollbackFor = Exception.class)
    public ResultVo useTicket(Long trId) {
        TicketRecord record = new TicketRecord();
        record.setId(trId);
        record.setStatus(TicketStatus.USED.getStatus());
        ticketRecordMapper.updateByPrimaryKeySelective(record);
        TicketRecord ticketRecord = ticketRecordMapper.getByKey(trId);
        ticketService.settlementOrderSplitInfo(ticketRecord, null);
        return ResultVo.ok();
    }

    /**
     * 积分流水明细
     *
     * @param mid
     * @param start
     * @param end
     * @param offset
     * @param limit
     * @return
     */
    @GetMapping("/integrallog/list")
    @ResponseBody
    @Auth
    public ResultVo listIntegralFlows(Long mid, Integer type, Date start, Date end, Integer offset, Integer limit) {
        if (null == offset) {
            offset = 0;
        }
        if (null == limit) {
            limit = 10;
        }
        PageUtils<IntegralLog> list = memberIntegralService.getIntegralLogsBefore(mid, type, start, end, offset, limit);
        ResultVo resultVo = new ResultVo();
        resultVo.put("success", true);
        resultVo.put("data", list);
        return resultVo;
    }


    @ApiOperation(value = "门店绑定聚合码")
    @GetMapping("/binding/aggregationCode")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "aggregationCode", value = "聚合码", paramType = "query", required = true),
    })
    @Auth
    public ResultVo bindingAggregationCode(@ApiIgnore @LoginUser Member member, @RequestParam(value = "aggregationCode") String aggregationCode) {
        if (member.getIsteam() != 3 && member.getIsClerk() != 1) {
            throw new BDException("只有商家能绑定聚合码");
        }
        //根据聚合码查询用户信息
        MemberAggregation memberResult = memberAggregationService.queryByCode(aggregationCode);
        if (memberResult != null) {
            throw new BDException("此聚合码已被绑定，请更换聚合码后再次提交");
        } else {
            MemberAggregation memberParam = new MemberAggregation();
            memberParam.setMid(member.getId());
            memberParam.setAggregationCode(aggregationCode);
            memberAggregationService.insert(memberParam);
        }
        ResultVo resultVo = new ResultVo();
        resultVo.put("data", "绑定成功");
        return resultVo;
    }


}
